<template>
	<view class="topic_practice_layout flex-column">
		<view class="z_paging_swiper">
			<z-paging-swiper>
				<template #top>
					<uni-nav-bar statusBar left-icon="back" @clickLeft="onClickLeft" right-text="交卷"
						@clickRight="onClickRight" :border="false"></uni-nav-bar>
				</template>
				<swiper :current="current" @change="swiperChange">
					<swiper-item v-for="(item, index) in data" :key="item._id" class="swiper_item">
						<scroll-view class="swiper_item_scroll_view" scroll-y :show-scrollbar='false'>
							<!-- 内容 -->
							<view class="container">
								<view class="container_tips flex-row">
									{{index + 1}} / {{data?.length}}
									<text class="container_type flex-1"> [{{stringFromValue(item.question_type)}}]
									</text>
									<view class="star-container" @click="favorite_click(item)">
										<uni-icons v-if="item.is_like" type="star-filled" size="28"
											color="#dd524d"></uni-icons>
										<uni-icons v-else type="star" size="28" color="#222222"></uni-icons>
									</view>
								</view>
							</view>
							<topic-practice-item :item="item" :showAnswer="showAnswer"></topic-practice-item>
						</scroll-view>
					</swiper-item>
					<!-- 答题卡 -->
					<swiper-item v-if="data?.length > 0" class="swiper_item flex-column">
						<view class="answer_sheet_container">
							<view v-for="(item,index) in data" :key="data._id" class="answer_sheet_item">
								<view class="answer_sheet_content">
									<view v-if="showAnswer"
										:class="['answer_sheet_item', item.is_answered ? 'answer_sheet_item_answered' : '']"
										@click="swiper_to_page(index)">
										{{index + 1}}
									</view>
									<view v-else
										:class="['answer_sheet_item', topic_has_select(item) ? 'answer_sheet_item_answered' : '']"
										@click="swiper_to_page(index)">
										{{index + 1}}
									</view>
								</view>
							</view>
						</view>
						<view class="flex-1"></view>
						<view class="answer_sheet_hand_paper flex-row centent-parent" @click="submit_paper">交卷并查看结果
						</view>
					</swiper-item>
				</swiper>
				<template #bottom>
					<!-- 上一题下一题 -->
					<view class="uni_pagination_container flex-column">
						<view class="uni_pagination flex-column">
							<uni-pagination prev-text="前一题" :next-text="next_text" :total="data ? data.length + 1 : 0"
								pageSize="1" :current="data ? current + 1 : 0" @change="uni_pagination_change">
							</uni-pagination>
						</view>
						<view class="safe-area-inset-bottom"></view>
					</view>
				</template>
			</z-paging-swiper>
		</view>
	</view>
</template>

<script setup>
	import {
		computed,
		ref,
		watch
	} from 'vue';

	import {
		onLoad
	} from "@dcloudio/uni-app"

	import {
		stringFromValue
	} from '@/utils/question.js'

	const questionsObj = uniCloud.importObject('questionsObj')
	const favorite = uniCloud.importObject('favoriteObj')
	const data = ref(null)
	const current = ref(0)
	/* 题库类型 0 模拟考试 1 历年真题 */
	const type = ref(null)
	/* 是否要在答完一题立刻显示答案 */
	const showAnswer = computed(() => type.value == '1')
	/* 题库id */
	let question_storehouse_id
	/* 提示语 */
	const next_text = ref('下一题')

	onLoad(async (params) => {
		type.value = params.type
		if (type.value == '1') {
			// 当前第几题
			current.value = params.current
		}
		// 题库id
		question_storehouse_id = params.question_storehouse_id
		// 数据
		let res = await questionsObj.storehouse_detail(question_storehouse_id)
		console.log('真题练习详情', res);
		if (res.errCode != 0) {
			return
		}
		if (res.data.length == 0) {
			uni.showModal({
				title: '温馨提醒',
				content: '暂无题目',
				showCancel: false,
				success: () => {
					uni.navigateBack()
				}
			})
		} else {
			data.value = res.data
			// 正确答案容器 + 笔记
			data.value.forEach(item => {
				item.user_answer = []
				if (!item.note) {
					item.note = {}
				}
			});
		}
		current.value = 0
	})

	/* 回答正确 */
	function isAnswerCorrect(params) {
		if ([0, 1, 2].includes(params.question_type)) {
			// 正确答案 和 你的选择 之间的差异
			let answer = params.answer.filter(obj => !params.user_answer.includes(obj))
			// 你的选择 和 正确答案 之间的差异
			let user_answer = params.user_answer.filter(obj => !params.answer.includes(obj))
			// 判断
			return answer.length == 0 && user_answer.length == 0
		} else if (params.question_type == 3) {
			// 填空题
			return params.answer_content == params.answer_fill_blanks
		}
		return false
	}

	async function favorite_click(params) {
		let res = await favorite.favorite(params._id, 2, params.is_like)
		if (res.errCode != 0) {
			return
		}
		params.is_like = !params.is_like
		uni.showToast({
			title: params.is_like ? '收藏成功' : '取消收藏成功',
			icon: 'success'
		})
	}

	function submit_paper() {
		let arrs = []
		if (showAnswer) {
			arrs = data.value.filter(item => topic_has_select(item) == 0)
		} else {
			arrs = data.value.filter(item => !item.is_answered)
		}
		if (arrs.length != 0) {
			uni.showModal({
				title: '温馨提醒',
				content: '你还有题目未做完，确认交卷吗？',
				success: (res) => {
					if (res.confirm) {
						hand_paper()
					}
				}
			})
		} else {
			hand_paper()
		}
	}

	const topic_exams = uniCloud.importObject('topic-exams')
	const topic_problem = uniCloud.importObject('topic-problem')
	const opendb_note = uniCloud.importObject('opendb-note')
	/* 提交考试 */
	async function hand_paper() {
		console.log("提交考试", data.value);
		let res1 = await topic_exams.openExam(Date.now(), question_storehouse_id)
		if (res1.errCode != 0) {
			return
		}
		// 拷贝一份
		let arrs = data.value.map(item => {
			return {
				topic_exams_id: res1.id,
				questions_topic_id: item._id,
				user_answer: item.user_answer,
				answer_content: item.answer_content,
				is_correct: isAnswerCorrect(item)
			}
		})
		// 提交试题
		let res2 = await topic_exams.answersForExam(arrs)
		let flag = res2.errCode == 0
		uni.showToast({
			title: flag ? '考试完成' : res2.errMsg,
			icon: flag ? 'success' : 'fail'
		})
		// 更新错题库
		if (!flag) {
			return
		}
		// 筛选出错误答案
		let wrong = arrs.filter(item => item.answer_content.length == 0 && !item.is_correct)
		// 提交错误答案
		let res3 = await topic_problem.topic_problem_add(wrong.map(item => item.questions_topic_id))
		// 筛选出笔记内容
		let notes = data.value.filter(item => {
			return item.note.content?.length > 0
		}).map(item => {
			item.note.topic_id = item._id
			return item.note
		})
		// 筛选笔记
		let res4 = await opendb_note.opendb_note_add(notes)
		console.log(res4);
		// 跳转到解析
		if (flag) {
			uni.redirectTo({
				url: '/pages_lianxi/linianzhenti/topic_practice_result?id=' + res1.id
			})
		}
	}

	function swiper_to_page(params) {
		current.value = params
	}

	function swiperChange(e) {
		current.value = e.detail.current
	}

	function uni_pagination_change(e) {
		current.value = e.current - 1
	}

	function topic_has_select(item) {
		if (item.question_type == 3) {
			return item.answer_content?.length > 0
		}
		return item.options.filter(item => item.isSelect).length > 0
	}

	/* 点击返回 */
	function onClickLeft() {
		uni.navigateBack()
	}

	/* 点击交卷 */
	function onClickRight() {
		current.value = data?.value.length
	}

	watch(() => current.value, (newValue, oldValue) => {
		if (data.value == undefined) {
			return
		}
		next_text.value = (current.value >= data.value.length - 1) ? '交 卷' : '下一题'
	}, {
		immediate: true
	})
</script>

<style lang="scss">
	page {
		height: 100%;
		width: 100%;
	}
</style>

<style lang="scss" scoped>
	.topic_practice_layout {
		height: 100%;
		width: 100%;

		.z_paging_swiper {
			flex: 1;
			width: 100%;

			swiper {
				height: 100%;
				width: 100%;

				.swiper_item {
					height: 100%;
					width: 100%;

					.swiper_item_scroll_view {
						height: 100%;
						overflow: scroll;

						.container {
							padding: 0 40rpx;

							.container_tips {
								align-items: center;
								font-size: 32rpx;
								margin-top: 24rpx;
								color: $me-color-gray-1;

								.container_type {
									margin-left: 8rpx;
									font-size: 32rpx;
									color: $me-color-blue;
								}

								.star-container {
									padding: 0 10rpx;
									justify-content: flex-end;
								}
							}

							.content {

								.content_text {
									color: $me-color-gray-1;
									font-size: 26rpx;
								}
							}
						}
					}

					.answer_sheet_container {
						padding: 40rpx 0;
						display: grid;
						gap: 30rpx 0rpx;
						grid-template-columns: repeat(5, 1fr);

						.answer_sheet_content {
							display: flex;
							align-items: center;
							justify-content: center;

							.answer_sheet_item {
								display: flex;
								align-items: center;
								justify-content: center;
								width: 70rpx;
								height: 70rpx;
								border: 1rpx solid $me-color-gray-4;
								border-radius: 50%;
								color: $me-color-blue;
							}

							.answer_sheet_item_answered {
								background-color: $me-color-blue;
								color: #fff;
								border: none
							}
						}

					}

					.answer_sheet_hand_paper {
						color: #fff;
						padding: 20rpx;
						font-size: 30rpx;
						background-color: $me-color-blue;
					}
				}
			}
		}

		.uni_pagination_container {
			border-top: 2rpx solid $me-color-background;

			.uni_pagination {
				justify-content: center;
				padding: 0 40rpx;
				height: 88rpx;
			}
		}

	}
</style>